#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"

#include "request.pb.h"

#include <iostream>

class Server
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MassagePtr;
    typedef std::shared_ptr<req::TranslateRequest> TranslateRequestPtr;
    typedef std::shared_ptr<req::AddRequest> AddRequestPtr;
    // onProtobufMessage 根据不同请求查找对应的回调函数
    // ProtobufCodec _codec; ProtobufCodec类内部的 onMessage 会对server收到的数据进行解析, 并调用onProtobufMessage
    // ProtobufCodec对象要传入一个分发器(_dispatcher), 用于解析数据后调用分发器对任务进行分发
    Server(int port) : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port),
                               "server", muduo::net::TcpServer::kReusePort),
                       _dispatcher(std::bind(&Server::onUnknownMessage, this,
                                             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
                       _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher,
                                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 注册业务处理函数
        _dispatcher.registerMessageCallback<req::TranslateRequest>(std::bind(&Server::onTranslate, this,
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<req::AddRequest>(std::bind(&Server::onAdd, this,
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        // 设置server收到数据后的消息处理回调(这里是解析数据, 然后根据数据进行分发任务)
        _server.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _server.setConnectionCallback(std::bind(&Server::onConnection, this, std::placeholders::_1));
    }
    void start() 
    {
        _server.start();
        _baseloop.loop();
    }
private:
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn,
                          const MessagePtr &message,
                          muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }
    std::string Translate(std::string &s)
    {
        std::unordered_map<std::string, std::string> map = {
            {"hello", "你好"},
            {"world", "世界"},
            {"hello world", "你好世界"},
        };
        auto it = map.find(s);
        if (it == map.end())
            return "没有此单词";
        else
            return it->second;
    }
    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateRequestPtr &message, muduo::Timestamp)
    {
        // 1. 提取message中的有效消息，也就是需要翻译的内容
        std::string req_msg = message->req();
        // 2. 进行翻译，得到结果
        std::string resp_msg = Translate(req_msg);
        // 3. 组织protobuf的响应
        req::TranslateResponse resp;
        resp.set_resp(resp_msg);
        // 4. 发送响应
        _codec.send(conn, resp);
    }
    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddRequestPtr &message, muduo::Timestamp)
    {
        int num1 = message->num1();
        int num2 = message->num2();
        int result = num1 + num2;
        req::AddResponse resp;
        resp.set_result(result);
        _codec.send(conn, resp);
    }
    void onConnection(const muduo::net::TcpConnectionPtr &conn) {
            if (conn->connected()) {
                LOG_INFO << "新连接建立成功！";
            }else {
                LOG_INFO << "连接即将关闭！";
            }
        }
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
    ProtobufDispatcher _dispatcher; // 任务分发(业务处理)
    ProtobufCodec _codec;           // 协议处理
};

int main()
{
    Server svr(8888);
    svr.start();
}